import { http } from '@/utils'
export const getArticle = () => {
  return async (dispatch) => {
    const res = await http.get('/channels')
    const { channels } = res.data.data
    dispatch({ type: 'article/Info', payload: channels })
  }
}
// 获取列表数据
export const getList = (params) => {
  return async (dispatch) => {
    const res = await http.get('/mp/articles', { params })
    const {
      page,
      per_page: pageSize,
      results: list,
      total_count: count,
    } = res.data.data

    dispatch({
      type: 'article/list',
      payload: {
        page,
        pageSize,
        list: list.map((item) => {
          return {
            ...item,
            cover: item.cover.images[0],
          }
        }),
        count,
      },
    })
  }
}
// 删除数据
export const delList = (id) => {
  return async (dispatch) => {
    await http.delete(`/mp/articles/${id}`)
  }
}
// 添加数据或编辑数据
export const updateArticle = (data, isDraft, isEdit) => {
  return async () => {
    if (isEdit) {
      // 编辑
      await http.put(`/mp/articles/${data.id}?draft=${isDraft}`, data)
    } else {
      // 发布
      await http.post(`/mp/articles?draft=${isDraft}`, data)
    }
  }
}
// 编辑
export const getArticleById = (article) => {
  return async (dispatch) => {
    const res = await http.get(`/mp/articles/${article}`)
    const {
      id,
      title,
      channel_id,
      content,
      cover: { type, images },
    } = res.data.data
    const articles = {
      id,
      title,
      channel_id,
      content,
      type,
      images,
    }
    dispatch({ type: 'article/getArticle', payload: articles })
    // 注意：此处需要将 文章详情数据 返回，这样，在页面中才能在请求后拿到该数据
    console.log(articles)
    return articles
  }
}
